package com.smartsofa.adapter;

import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.util.AsyncImageLoader;
import com.smartsofa.util.MyUtils;

public class SearchUserAdapter extends BaseAdapter {

	private ProgressDialog mDialog;
	private String url;
	private Boolean flag = false;
	private String reg_msg;
	private JSONObject json;
	// 定义网络连接超时判定变量
	private boolean network_timeout = false;

	private List<Map<String, Object>> mData;
	private LayoutInflater mInflater;
	private Context mContext;

	ViewHolder holder;
	Dialog dialog;
	int familyId;
	//异步加载图片
	private AsyncImageLoader imageLoader;

	public SearchUserAdapter(Context context, List<Map<String, Object>> data,
			int familyId) {
		this.mInflater = LayoutInflater.from(context);
		this.mContext = context;
		this.mData = data;
		this.familyId = familyId;
		imageLoader = new AsyncImageLoader(context);
	}

	protected final class ViewHolder {
		public ImageView user_img;
		public TextView tv_username;
		public Button bt_confirm_add;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mData.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return mData.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {
		// TODO Auto-generated method stub
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater
					.inflate(R.layout.listview_search_user, null);

			holder.user_img = (ImageView) convertView
					.findViewById(R.id.search_user_img);
			holder.tv_username = (TextView) convertView
					.findViewById(R.id.tv_search_username);
			holder.bt_confirm_add = (Button) convertView
					.findViewById(R.id.bt_confirm_add);
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.user_img.setBackgroundResource(R.drawable.user_img2);
	     // 预设一个图片
  		holder.user_img.setBackgroundResource(R.drawable.user_img2);
  		if (mData.get(position).containsKey("userImg")&&!("").equals(mData.get(position).get("userImg"))) {
  			final String imgUrl = (String) mData.get(position).get("userImg");
  			System.out.println("imgUrl..........."+imgUrl);
  			// 给 ImageView 设置一个 tag
  			holder.user_img.setTag(imgUrl);
  			if (!TextUtils.isEmpty(imgUrl)) {
  				Bitmap bitmap = imageLoader.loadImage(holder.user_img, imgUrl);
  				if (bitmap != null) {
  					holder.user_img.setImageBitmap(bitmap);
  				}
  			}
  		}
		holder.tv_username.setText(mData.get(position).get("userName")
				.toString());
		holder.bt_confirm_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				LinearLayout layout = (LinearLayout) mInflater.inflate(
						R.layout.invite_dialog, null);
				dialog = new Dialog(parent.getContext(),
						R.style.FullHeightDialog);
				dialog.getWindow().setGravity(Gravity.CENTER);
				dialog.getWindow().setContentView(layout);
				// requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setCancelable(false);
				dialog.show();
				final EditText et_verifymsg = (EditText) layout
						.findViewById(R.id.et_verifymsg);
				Button bt_submit_invite = (Button) layout
						.findViewById(R.id.bt_submit_invite);
				bt_submit_invite.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						String verifymsg = et_verifymsg.getText().toString();
						int invitedid = (Integer) mData.get(position).get(
								"userID");
						Thread thread = new Thread(new invite_thread(familyId,
								invitedid, verifymsg));
						thread.start();
						mDialog = new ProgressDialog(parent.getContext());
						mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
						mDialog.setMessage("处理中，请稍候...");
						mDialog.show();
					}
				});
				Button bt_submit_cancle = (Button) layout
						.findViewById(R.id.bt_submit_cancle);
				bt_submit_cancle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
			}
		});
		return convertView;
	}

	class invite_thread implements Runnable {
		int familyid;
		int invitedid;
		String verifymsg;

		public invite_thread(int familyid, int invitedid, String verifymsg) {
			this.familyid = familyid;
			this.invitedid = invitedid;
			this.verifymsg = verifymsg;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				url = MyUtils.getUrl() + "family_inviteMember?userid="
						+ MyUtils.getUSERID() + "&familyid=" + familyid
						+ "&invitedid=" + invitedid + "&verifyMsg=" + verifymsg;
				HttpGet request = new HttpGet(url);
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,
						MyUtils.REQUEST_TIMEOUT);
				HttpClient httpClient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpClient.execute(request);

				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					network_timeout = true;
					String jsonString = EntityUtils.toString(httpResponse
							.getEntity());
					json = new JSONObject(jsonString);
					flag = json.getBoolean("success");
					reg_msg = json.getString("msg");
					Message msg = content_handler.obtainMessage();
					if (network_timeout) {
						if (flag) {
							msg.what = 1;

						} else {
							msg.what = 2;
						}
					} else {
						msg.what = 3;
					}
					content_handler.sendMessage(msg);

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {
			mDialog.dismiss();
			dialog.dismiss();
			switch (msg.what) {
			case 1:
				Toast.makeText(mContext, "已发出邀请！", Toast.LENGTH_SHORT).show();
				break;
			case 2:
				Toast.makeText(mContext, reg_msg.toString(), Toast.LENGTH_SHORT)
						.show();
				break;
			case 3:
				Toast.makeText(mContext, "网络连接超时!", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

}
